package com.zenithmind.user.controller;

import com.zenithmind.common.annotation.Log;
import com.zenithmind.common.constant.OperationTypeEnum;
import com.zenithmind.common.result.Result;
import com.zenithmind.user.controller.base.BaseController;
import com.zenithmind.user.pojo.domain.User;
import com.zenithmind.user.pojo.domain.UserRole;
import com.zenithmind.user.pojo.dto.UserProfileUpdateDTO;
import com.zenithmind.user.pojo.vo.UserVO;
import com.zenithmind.user.service.domain.UserManagementService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 * 遵循单一职责原则：专门处理用户管理相关功能
 * 遵循开闭原则：通过策略模式支持不同的管理操作
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/user-management")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户管理相关接口，包括用户信息修改、状态管理、角色分配等")
public class UserManagementController extends BaseController {

    private final UserManagementService userManagementService;

    /**
     * 添加或修改用户信息接口
     */
    @Log(description = "添加或修改用户信息", operationType = OperationTypeEnum.UPDATE)
    @PostMapping("/addOrUpdateUser")
    @Operation(summary = "添加或修改用户信息", description = "管理员添加或修改用户信息")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<UserVO> addOrUpdateUser(@Valid @RequestBody User user) {
        logOperation("添加或修改用户信息", user.getId(), user.getUsername());
        
        try {
            UserVO userVO = userManagementService.addOrUpdateUser(user);
            logSuccess("添加或修改用户信息", userVO.getUsername());
            return success(userVO);
        } catch (Exception e) {
            logFailure("添加或修改用户信息", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改当前登录的用户信息接口
     */
    @Log(description = "修改当前登录用户信息", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateProfile")
    @Operation(summary = "修改当前登录的用户信息", description = "用户修改自己的档案信息")
    public Result<UserVO> updateProfile(@Valid @RequestBody UserProfileUpdateDTO updateDTO) {
        logOperation("修改当前登录用户信息", updateDTO.getNickname());
        
        try {
            UserVO userVO = userManagementService.updateProfile(updateDTO);
            logSuccess("修改当前登录用户信息", userVO.getUsername());
            return success(userVO);
        } catch (Exception e) {
            logFailure("修改当前登录用户信息", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改用户状态接口
     */
    @Log(description = "修改用户状态", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateStatus")
    @Operation(summary = "修改用户状态", description = "管理员修改用户状态（启用/禁用）")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<UserVO> updateStatus(@Valid @RequestBody User user) {
        logOperation("修改用户状态", user.getId(), user.getStatus());
        
        try {
            UserVO userVO = userManagementService.updateStatus(user);
            logSuccess("修改用户状态", userVO.getUsername() + " 状态更新为: " + user.getStatus());
            return success(userVO);
        } catch (Exception e) {
            logFailure("修改用户状态", e.getMessage());
            throw e;
        }
    }

    /**
     * 启用用户接口
     */
    @Log(description = "启用用户", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/enable/{userId}")
    @Operation(summary = "启用用户", description = "管理员启用指定用户")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<Void> enableUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        
        logOperation("启用用户", userId);
        
        try {
            userManagementService.enableUser(userId);
            logSuccess("启用用户", userId);
            return success();
        } catch (Exception e) {
            logFailure("启用用户", e.getMessage());
            throw e;
        }
    }

    /**
     * 禁用用户接口
     */
    @Log(description = "禁用用户", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/disable/{userId}")
    @Operation(summary = "禁用用户", description = "管理员禁用指定用户")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<Void> disableUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        
        logOperation("禁用用户", userId);
        
        try {
            userManagementService.disableUser(userId);
            logSuccess("禁用用户", userId);
            return success();
        } catch (Exception e) {
            logFailure("禁用用户", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改用户角色接口
     */
    @Log(description = "修改用户角色", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateRole")
    @Operation(summary = "修改用户角色", description = "管理员修改用户角色")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<UserVO> updateUserRole(@Valid @RequestBody UserRole userRole) {
        logOperation("修改用户角色", userRole.getUserId(), userRole.getRoleId());
        
        try {
            UserVO userVO = userManagementService.updateRole(userRole);
            logSuccess("修改用户角色", userVO.getUsername() + " 角色更新完成");
            return success(userVO);
        } catch (Exception e) {
            logFailure("修改用户角色", e.getMessage());
            throw e;
        }
    }

    /**
     * 分配角色给用户
     */
    @Log(description = "分配角色给用户", operationType = OperationTypeEnum.UPDATE)
    @PostMapping("/assignRole")
    @Operation(summary = "分配角色给用户", description = "管理员为用户分配角色")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<Void> assignRole(
            @Parameter(description = "用户ID", required = true)
            @RequestParam @NotBlank(message = "用户ID不能为空") String userId,
            @Parameter(description = "角色ID", required = true)
            @RequestParam @NotBlank(message = "角色ID不能为空") String roleId) {
        
        logOperation("分配角色给用户", userId, roleId);
        
        try {
            userManagementService.assignRole(userId, roleId);
            logSuccess("分配角色给用户", "用户 " + userId + " 分配角色 " + roleId + " 成功");
            return success();
        } catch (Exception e) {
            logFailure("分配角色给用户", e.getMessage());
            throw e;
        }
    }

    /**
     * 移除用户角色
     */
    @Log(description = "移除用户角色", operationType = OperationTypeEnum.UPDATE)
    @DeleteMapping("/removeRole")
    @Operation(summary = "移除用户角色", description = "管理员移除用户的角色")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<Void> removeRole(
            @Parameter(description = "用户ID", required = true)
            @RequestParam @NotBlank(message = "用户ID不能为空") String userId,
            @Parameter(description = "角色ID", required = true)
            @RequestParam @NotBlank(message = "角色ID不能为空") String roleId) {
        
        logOperation("移除用户角色", userId, roleId);
        
        try {
            userManagementService.removeRole(userId, roleId);
            logSuccess("移除用户角色", "用户 " + userId + " 移除角色 " + roleId + " 成功");
            return success();
        } catch (Exception e) {
            logFailure("移除用户角色", e.getMessage());
            throw e;
        }
    }

    /**
     * 重置用户密码接口
     */
    @Log(description = "重置用户密码", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/resetPassword")
    @Operation(summary = "重置用户密码", description = "管理员重置用户密码")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    public Result<Void> resetPassword(@Valid @RequestBody User user) {
        logOperation("重置用户密码", user.getId());
        
        try {
            userManagementService.resetPassword(user);
            logSuccess("重置用户密码", user.getId());
            return success();
        } catch (Exception e) {
            logFailure("重置用户密码", e.getMessage());
            throw e;
        }
    }

    /**
     * 更新用户存储使用量接口
     */
    @Log(description = "更新用户存储空间使用情况", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateStorageUsed")
    @Operation(summary = "更新用户已用存储空间", description = "更新用户的存储空间使用情况")
    public Result<Void> updateStorageUsed(
            @Parameter(description = "用户ID", required = true)
            @RequestParam("userId") @NotBlank(message = "用户ID不能为空") String userId,
            @Parameter(description = "文件大小变化量（字节）", required = true)
            @RequestParam("fileSize") long fileSize) {
        
        logOperation("更新用户存储空间", userId, fileSize);
        
        try {
            boolean success = userManagementService.updateStorageUsed(userId, fileSize);
            if (success) {
                logSuccess("更新用户存储空间", "用户 " + userId + " 存储空间更新成功");
                return success();
            } else {
                logFailure("更新用户存储空间", "存储空间不足或更新失败");
                return fail("存储空间不足或更新失败");
            }
        } catch (Exception e) {
            logFailure("更新用户存储空间", e.getMessage());
            throw e;
        }
    }

    /**
     * 批量删除用户接口
     */
    @Log(description = "批量删除用户", operationType = OperationTypeEnum.DELETE)
    @DeleteMapping("/deleteBatch")
    @Operation(summary = "批量删除用户", description = "管理员批量删除用户")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public Result<Void> deleteBatch(
            @Parameter(description = "要删除的用户ID列表", required = true)
            @RequestBody @NotEmpty(message = "用户ID列表不能为空") List<String> ids) {
        
        logOperation("批量删除用户", ids.size() + " 个用户");
        
        try {
            if (ids.size() > 50) {
                return fail("批量删除用户数量不能超过50个");
            }
            
            userManagementService.deleteBatch(ids);
            logSuccess("批量删除用户", "成功删除 " + ids.size() + " 个用户");
            return success();
        } catch (Exception e) {
            logFailure("批量删除用户", e.getMessage());
            throw e;
        }
    }

    /**
     * 删除单个用户接口
     */
    @Log(description = "删除用户", operationType = OperationTypeEnum.DELETE)
    @DeleteMapping("/{userId}")
    @Operation(summary = "删除用户", description = "管理员删除指定用户")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public Result<Void> deleteUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        
        logOperation("删除用户", userId);
        
        try {
            userManagementService.deleteUser(userId);
            logSuccess("删除用户", userId);
            return success();
        } catch (Exception e) {
            logFailure("删除用户", e.getMessage());
            throw e;
        }
    }
}
